package com.sjy.mvvmdemo.roomdb

import android.util.Log
import androidx.databinding.Bindable
import androidx.databinding.Observable
import androidx.databinding.PropertyChangeRegistry
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.sjy.mvvmdemo.roomdb.db.UserEntity
import com.sjy.mvvmdemo.roomdb.dbfactory.UserRepository
import kotlinx.coroutines.launch

/**
 * Activity的绑定ViewModel 和xml的交互都由该vm处理
 * 使用ViewModel进行数据绑定的实现方式：实现Observable接口+@Bindable注解，如果act中加监听，添加LiveData<>即可
 * 推荐使用LiveData
 */
class SecondViewModel(private val mUserRepository: UserRepository) : ViewModel(), Observable {
    val userLists = mUserRepository.userLists

    //==============================错误信息-liveData方法==============================
    //错误信息
    private val statusMessage = MutableLiveData<String>()

    //将信息返回给act处理信息
    val msg: LiveData<String>
        get() = statusMessage

    //==============================错误信息-liveData方法==============================


    //==============================（1）Observable数据绑定方式==============================
    // @Bindable+MutableLiveData<String>(),在xml中绑定该属性： android:text="@={mMainViewModel.mName}"，即可双向绑定
    @Bindable
    val inputUser = MutableLiveData<String>()

    @Bindable
    val inputPass = MutableLiveData<String>()


    //保存按钮监听
    fun saveData() {
        if (inputUser.value == null) {
            statusMessage.value = "请输入账号"
        } else if (inputPass.value == null) {
            statusMessage.value = "请输入密码"
        } else {
            //数据库保存
            viewModelScope.launch {
                //数据新增，插入第一个位置
                val newRowId = mUserRepository.insert(
                    UserEntity(
                        _id = 0,
                        user = inputUser.value.toString(),
                        pass = inputPass.value.toString()
                    )
                )
                if (newRowId > -1) {
                    statusMessage.value = "数据保存成功 $newRowId"
                } else {
                    statusMessage.value = "数据保存失败 $newRowId"
                }
                inputUser.value = null
                inputPass.value = null
            }

        }
    }

    fun deleteAll() {
        viewModelScope.launch {
            val noOfRowsDeleted = mUserRepository.deleteAll()
            if (noOfRowsDeleted > 0) {
                statusMessage.value = "数据清空成功$noOfRowsDeleted"
            } else {
                statusMessage.value = "数据清空失败$noOfRowsDeleted"
            }
        }
    }

    /**
     * 更新输入内容
     */
    fun showView(mUser: UserEntity) {
        inputUser.value = mUser.user
        inputPass.value = mUser.pass
    }

    //==============================Observable的两个复写方法：Observable实现数据的绑定==============================

    //https://blog.csdn.net/qq_29983773/article/details/100656485
    private val callbacks: PropertyChangeRegistry by lazy { PropertyChangeRegistry() }
    override fun removeOnPropertyChangedCallback(callback: Observable.OnPropertyChangedCallback?) {

        Log.d("SJY", "removeOnPropertyChangedCallback")
//        callbacks.add(callback)
    }

    override fun addOnPropertyChangedCallback(callback: Observable.OnPropertyChangedCallback?) {
        Log.d("SJY", "addOnPropertyChangedCallback")
//        callbacks.remove(callback)
    }

}